package com.fpp.nettyV3;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

public class TCPClient {
    public static void main(String[] args) {
        ClientBootstrap bootstrap = new ClientBootstrap(
                new NioClientSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()
                )
        );

        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() {
                SimpleChannelHandler channelHandler = new SimpleChannelHandler() {
                    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
                        System.out.println("Received message: " + e.getMessage().toString());
                    }
                };
                return Channels.pipeline(new StringDecoder(),channelHandler,new StringEncoder());
            }
        });

        bootstrap.connect(new InetSocketAddress("localhost", 1881));
        System.out.println("TCP client connected to localhost:8888.");
    }
}